#include <pthread.h> // 带入线程库
#include <iostream>
#include <unistd.h>

// 票数
int tickets = 1000;

// 线程执行的函数
void *Grab_tickets(void *args)
{
    std::string threadname = static_cast<const char *>(args);

    while (true)
    {
        if (tickets > 0)
        {
            // 抢票: 
            usleep(100); // 抢票花费时间
            std::cout << threadname << " is running... tickets = " << tickets << std::endl;
            tickets--;
        }
        else{
            // 没有票的情况就推出: 
            break;
        }
    }
    return nullptr;
}

const int N = 5;

int main()
{
    pthread_t t[N];

    // 创建五个线程执行抢票
    for (int i = 0; i < N; i++)
    {
        std::string name = "thread-" + std::to_string(i + 1);
        pthread_create(t + i, nullptr, Grab_tickets, (void *)name.c_str());
    }

    for (int i = 0; i < N; i++)
    {
        pthread_join(t[i], nullptr);
    }

    return 0;
}

